package com.imooc.springboot.producer;

import com.imooc.springboot.entity.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.UUID;

import java.util.Map;

@Component
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //成功
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {

        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("correlationData:"+correlationData);
            System.out.println("ack:"+ack);
            if(!ack){
                System.out.println("异常处理");
            }else{
                //System.out.println("更新数据库");
            }
            System.out.println("cause:"+cause);
        }
    };

    //失败
    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode,
                                    String replyText, String exchange, String routingKey) {
            System.out.println("return exchange:"+exchange+", routingKey:"+routingKey+
                    ", replyCode:"+replyCode+", replyText:"+replyText);
        }
    };

    public void send(Object message, Map<String, Object> properties){
        MessageHeaders mhs = new MessageHeaders(properties);
        Message msg = MessageBuilder.createMessage(message, mhs);
        rabbitTemplate.setConfirmCallback(confirmCallback);  //支持消息确认
        rabbitTemplate.setReturnCallback(returnCallback);  //支持消息返回
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString()); //全局唯一
        rabbitTemplate.convertAndSend("exchange-1","springboot.hello",msg,correlationData);
    }

    public void sendOrder(Order order) {

        rabbitTemplate.setConfirmCallback(confirmCallback);  //支持消息确认
        rabbitTemplate.setReturnCallback(returnCallback);  //支持消息返回
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString()); //全局唯一
        rabbitTemplate.convertAndSend("exchange-2","springboot.abc",order,correlationData);
    }
}
